import os,copy,sys,glob
import pyenvconf

class upcase_dict (dict):
    def __setitem__ (self, key, value):
        dict.__setitem__(self, key.upper(), value)

    def __getitem__ (self, key):
        return dict.__getitem__(self, key.upper())

    def get (self, key, default=None):
        return dict.get(self, key.upper())

    def has_key (self, key):
        return dict.has_key(self, key.upper())

def mk_envfile(env,newdir = None):
    print env
    if sys.platform == 'win32':
        lineformat = 'set %s=%s\n'
        filename = 'envsetfrompy.bat'
    else:
        lineformat = 'export %s=%s\n'
        filename = 'envsetfrompy'

    lines = [lineformat % (var, val) for (var,val) in env.items()]
    f = open(filename,"w")
    f.write(''.join(lines))
    if newdir:
        newdir = os.path.abspath(newdir)
        if sys.platform == 'win32':
            drive, newdir = os.path.splitdrive(newdir)
        if drive:
            f.write(drive+"\n")
            
        f.write("cd " + newdir)
        


def find_env_file(f):
    tries = [f,os.path.join(pyenvconf.envfile_search_dir, f)]
    tries.extend(glob.glob(f+"*") +
                 glob.glob(os.path.join(pyenvconf.envfile_search_dir, f) +"*"))
    for t in tries:
        if os.path.isfile(t):
            return os.path.abspath(t)
    print "Can't find envfile for:",f


def run_envlets(envlets):
    envscripts = [find_env_file(f) for f in envlets]
    envscripts = filter(None, envscripts)

    #print "Will get env from:",envscripts
    origenv = upcase_dict(os.environ)

    newenv = upcase_dict(origenv)

    scriptenv = {}

    scriptenv['e'] = newenv
    scriptenv['curdir'] = os.getcwd()

    for envscript in envscripts:
        exec open(envscript) in scriptenv,scriptenv

    sdict = scriptenv["e"]

    changes = {}
    for k,v in origenv.items():
        if k not in sdict:
            changes[k] = None
            continue
        if v != sdict[k]:
            changes[k] = sdict[k]

    for k,v in sdict.items():
        if k not in origenv:
            changes[k] = v

    return changes, scriptenv


def manipulate_current_environ(*envlets):
    """ only manipulate os.environ, to be used from py scripts """
    changes, scriptenv = run_envlets(envlets)
    for k, v in changes.items():
        os.environ[k] = v

def main():
    changes, scriptenv = run_envlets(sys.argv[1:])
    mk_envfile(changes,
               scriptenv['curdir'] != os.getcwd() and
               scriptenv['curdir'] or None)

if __name__ == "__main__":
    main()
